import { stringify, getBoundingClientRect, getDomPath } from "./utils";
import { addLog } from "@/api/user.js";
class Tracker {
  constructor() {
    document.addEventListener(
      "click",
      (event) => {
        try {
          let code = event.target.getAttribute("data-tracker");
          const eventPaths =
            event.path || (event.composedPath && event.composedPath()) || [];
          //   拿不到目标元素的点，找path上的
          if (!code) {
            for (let i = 1; i < 4; i++) {
              if (
                eventPaths[i] &&
                eventPaths[i].getAttribute &&
                eventPaths[i].getAttribute("data-tracker")
              ) {
                code = eventPaths[i].getAttribute("data-tracker");
                break;
              }
            }
          }
          if (!code) return;
          //   const domPath = getDomPath(event.target, false);
          //   const data = {
          //     code,
          //     XPath: encodeURIComponent(domPath),
          //     text: document.title + "-" + event.target.innerText,
          //     type: event.type,
          //   };
          Tracker.send(event.type, code);
        } catch (error) {}
      },
      true
    );
  }

  /**
   *
   * @param {*} type 类型 'enter' 进入 || 'click' 点击
   * @param {*} code 点
   * @param {*} ext 其余信息
   */
  static send(type, code, ext = {}) {
    Tracker._send({
      type,
      code,
      ext,
    });
  }
  static _send(data = {}) {
    const user = JSON.parse(localStorage.getItem("user"));
    const params = {
      ...data,
      ...user,
      button_name_list: undefined,
      domain: document.domain,
      w: document.body.clientWidth,
      h: document.body.clientHeight,
      url: encodeURIComponent(document.URL),
      t: new Date().getTime(),
      ua: navigator.userAgent,
      pid: 1,
    };
    addLog(params);
  }
}
export default Tracker;
